<?php
/**
 *
 */
namespace app\home\controller\cart;

use app\home\controller\Base;
use app\common\query\MallGoods;
use think\Request;
class Handle extends Base
{

	private $params;

	public function __construct(){
		 parent::__construct();
		// //token验证
		// if(false == Base::checkToken()){
		// 	$this->error('token error!');
		// }
		// // 参数去token
		$params = $this->request->param();
		//unset($params['token']);
		$this->params = $params;
	}

    /**
     * [addcart 添加购物车]
     * @return [type] [description]
     */
	public function addcart(){
        $param = $this->params;
        $param['create_time'] = time();
        $model = new MallGoods();
        $param['price'] = $model::getValue(['id'=>$param['id']],'price');
        $credit = $model::getValue(['id'=>$param['id']],'credit');
        $param['credit'] = intval($credit)*intval($param['number']);
        $res[$param['id']] = $param;
        //购物车中是否有值
        if(true === $this->checkCart()){
            $row = cookie('cartlist');

            foreach ($row as $key => $v){
                //判断购物车商品是否存在.存在则相加
            	if($key == $param['id']){
                        $res[$key]['number'] = intval($v['number']) + intval($param['number']);
                        $res[$key]['credit'] = intval($v['credit']) + intval($param['credit']);
            	}else{
                //不存在,则原有数据赋值
            		$res[$key]=$v;
            	}
            }
        }
        cookie('cartlist',$res,'864000');
        return json(['code'=>200,'msg'=>'添加成功']);
	}


    /**
     * [addcart 购物车列表增减]
     * @return [type] [description]
     */
    public function addcartlist(){
        $param = $this->params;
        $res[$param['id']] = $param;
        $row = cookie('cartlist');
        $model = new MallGoods();
        $credit = $model::getValue(['id'=>$param['id']],'credit');
        foreach ($row as $key => $v){
            //判断购物车商品是否存在.存在则相加
            if($key == $param['id']){
                    $res[$key]['number'] =intval($param['number']);
                    $res[$key]['credit'] = intval($credit)*intval($param['number']);
                    $res[$key]['price'] = intval($v['price']);
            }else{
            //不存在,则原有数据赋值
                $res[$key]=$v;
            }
        }
        cookie('cartlist',$res,'864000');
        return json(['code'=>1,'msg'=>'success']);
    }
    /*
    **
    *如果加入订单了，则删除购物车中的商品
     */
    public function deleteCart($gid=''){
        if(true === $this->checkCart()){
            $row = cookie('cartlist');
            $res = [];
            foreach ($row as $key => $v){
                if($key == $gid){
                    unset($res[$key]);
                }else{
                    $res[$key]=$v;
                }
            }
        }
        cookie('cartlist',$res,'864000');
    }

	public function checkCart(){
        $data = cookie('cartlist');
        if($data){
        	return true;
        }
        return false;
	}

}